package com.example.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.mapper.OperateLogMapper;
import com.example.pojo.OperateLog;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {
    //直接拿到当前请求的请求对象
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.example.anno.MyLog)")//切入点表达式
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();

        //获取操作人ID(当前登录员工ID)
        String jwt = request.getHeader("token");//获取jwt令牌
        /*  解析jwt令牌
            得到的是自己创建的Map集合，里面有自己put加入的员工信息*/
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");

        //获取操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //获取操作类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();

        //获取操作方法名
        String methodName = proceedingJoinPoint.getSignature().getName();

        //获取操作方法参数
        Object[] args = proceedingJoinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        //调用原始方法
        Object proceed = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();

        //获取返回值
        String returnValue = JSONObject.toJSONString(proceed);

        //获取操作耗时
        long costTime = end -start;

        OperateLog operateLog = new OperateLog();

        operateLog.setOperateUser(operateUser);
        operateLog.setOperateTime(operateTime);
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(methodParams);
        operateLog.setReturnValue(returnValue);
        operateLog.setCostTime(costTime);

        //记录操作日志
        operateLogMapper.insert(operateLog);

        log.info("AOP记录操作日志：{}",operateLog);


        return proceed;
    }
}
